import axios from 'axios'
import { stringify } from 'qs'

import { info } from '../utils/output'
import checker from '../utils/checker'
import { retransmission, frequencyLimit } from '../utils/interceptors'
import setHeaders from '../utils/header'
import { codeParser, responsParser } from '../utils/parser'

import CreditModel from '../model/credit.model'
import HeaderModel from '../model/header.model'
import UserinfoModel from '../model/userinfo.model'

// 设置超时重传、控制请求频率（拦截器设置是全局的，对后面的请求都会生效）
retransmission()
frequencyLimit()

const getCredit = async (url: string): Promise<CreditModel> => {
  // 获取 token 并加入到请求头中 以 cookie 的形式携带
  const { headers: header, data } = await axios.get(url)
  const cookie = header?.['set-cookie']?.[0]!
  checker(cookie, '', '无法获取token')
  const headers = setHeaders(cookie)
  // 解析页面上的验证码
  const code = codeParser(data)!
  checker(code, '', '无法获取code')
  return { code, headers }
}

const registerToken = async (
  url: string,
  userinfo: UserinfoModel,
  code: string,
  headers: HeaderModel
): Promise<void> => {
  // 使用帐号密码和验证码登陆
  const { username, userpwd } = userinfo
  const { data: page } = await axios.post(
    url,
    stringify({
      username,
      userpwd,
      code,
      login: 'login',
      checkcode: '1',
      rank: '0',
      action: 'login',
      m5: '1'
    }),
    // 避免丢失索引签名
    { headers: { ...headers } }
  )
  checker(page.includes('控制面板'), userinfo.username + ' 登陆成功', responsParser(page)!)
}

const login = async (url: string, userinfo: UserinfoModel): Promise<HeaderModel> => {
  info(userinfo.username + ' 已加入任务队列')
  const { code, headers } = await getCredit(url)
  await registerToken(url, userinfo, code, headers)
  return headers
}

export default login
